package com.yamibuy.ec.resource.handler;

import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.yamibuy.ec.resource.aws.AwsS3Util;
import com.yamibuy.ec.resource.domain.ImageRule;
import com.yamibuy.ec.resource.domain.WatermarkRule;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.filters.Watermark;
import net.coobird.thumbnailator.geometry.Coordinate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 图片处理
 *
 * @author: damon.li
 * @version: 2021年02月23日 8:33
 */
@Component
@Slf4j
public class GifHandler implements RequestHandlerFlag<String> {

	/**
	 * 需要处理的图片格式
	 */
	private static final String handleImagePathReg = "(^(/\\w+)+/\\w{32}_(.+)\\.(gif|GIF)$)|(^(/\\w+)+/\\w{32}\\.?(gif|GIF)?$)|(^(/\\w+).+\\.(gif|GIF)$)";

	@Resource
	private AwsS3Util awsS3Util;

	@Override
	public ByteArrayOutputStream handle(String requestKeyRule) throws Exception {
		log.debug("收到GIF图片请求: {} ", requestKeyRule);
		ImageRule imageRule = new ImageRule(requestKeyRule);
		log.debug("GIF图片请求参数：{}", imageRule.toString());
		String fileKey = imageRule.getFileKey();
		log.debug("GIF图片路径：{}", fileKey);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		BufferedImage image = awsS3Util.getImage(fileKey);
		Img.from(image).write(out);
		return out;
	}

	@Override
	public boolean flag(String path) {
		boolean matches = path.matches(handleImagePathReg);
		return matches;
	}

	@Override
	public RequestHandlerFlag responseHeader(ServletResponse servletResponse) {
		servletResponse.setContentType(MediaType.IMAGE_GIF_VALUE);
		servletResponse.setCharacterEncoding(Charset.defaultCharset().name());
		return this;
	}
}
